package com.cfgj.web.websocket;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/websocket/{roomName}")
public class WebSocket {
	private static String msg;
	private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap();


	@OnMessage
	public void onMessage(@PathParam("roomName") String roomName,
						  String msg, Session session) throws IOException, InterruptedException{


	    // Send a final message to the client

		String message;
		//可以在此保存数据到数据库

		for (Session session1 : rooms.get(roomName)) {
			 System.out.println("session1:"+session1);
			//判断是否发送给自己
			if(session1.equals(session)) {
				//发送给自己
				message = "<button type='button' th:onclick='send1()' value='发送'>发送</button>";
			}else {
				//发送给别人
				message = "ok";	}
			//发送
			session1.getBasicRemote().sendText(message);

		}

	}
	
	@OnOpen
	public void onOpen(@PathParam("roomName") String roomName, Session session){
		if (!rooms.containsKey(roomName)) {
			// 创建房间不存在时，创建房间
			Set<Session> room = new HashSet<>();
			// 添加用户
			room.add(session);
			rooms.put(roomName, room);
		} else {
			// 房间已存在，直接添加用户到相应的房间
			rooms.get(roomName).add(session);
		}
		 System.out.println("session:"+session);
		System.out.println("a client has connected!");

	}

	@OnClose
	public void disConnect(@PathParam("roomName") String roomName, Session session) {
		rooms.get(roomName).remove(session);
		System.out.println("a client has disconnected!");
	}
	
}
